package com.example.service;

import com.example.entity.*;
import com.example.Repository.CategoryRepository;
import com.example.Repository.ProductRepository;
import com.example.mapper.CategoryMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductRepository productRepository;

    public List<CategoryWithProducts> findAllCategories() {
        List<Category> categories = categoryMapper.findcategoryAll(); // 检索所有类别
        List<CategoryWithProducts> result = new ArrayList<>();

        for (Category category : categories) {
            CategoryWithProducts categoryDTO = new CategoryWithProducts();
            categoryDTO.setId(category.getId());
            categoryDTO.setName(category.getName());
            categoryDTO.setSort(category.getSort());

            List<Menu> products = productRepository.findBycategoryId(category.getId()); // 根据类别检索产品
            List<Product> productDTOs = new ArrayList<>();

            for (Menu product : products) {
                Product productDTO = new Product();
                productDTO.setMenuId(product.getMenuId());
                // 设置其他属性...
                productDTO.setMenuName(product.getMenuName());
                productDTO.setMenuPrice(product.getMenuPrice());
                productDTO.setCategory_id(product.getCategoryId());
                productDTO.setIs_single(product.getIs_single());

                productDTO.setMenuImage(product.getMenuImage());
                productDTOs.add(productDTO);
            }

            categoryDTO.setProducts(productDTOs);
            result.add(categoryDTO);
        }
        return result;
    }
    public void updata(Category category) {
        categoryMapper.updata(category);
    }

    public void add(Category category) {
        categoryMapper.insert(category);
    }

    public void delete(Integer id) {
        categoryMapper.delete(id);
    }

    public List<Category> findCategories() {
        return categoryMapper.findcategoryAll();
    }

    public PageBean page(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        List<Category> pageList=categoryMapper.selectByPage(name);
        Page<Category> p=(Page<Category>) pageList;
        PageBean pageBean=new PageBean(p.getTotal(),p.getResult());
        return pageBean;
    }

}
